from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings
from afast_core.core_libs.redis.syncredis import SyncRedisClient


class SyncRedisPluginClient(SyncRedisClient, BasePlugin):
    '''
    使用示例：
    SyncRedisPluginClient(core_app=core_app, configs=SyncRedisPluginClient.RedisSettings(
    host='127.0.0.1', port=6379
    ))
    '''
    # 设置插件默认的参数信息
    name = 'SyncRedis'

    class RedisSettings(Settings):
        password: str = None
        db: int = 0
        host: str = "localhost"
        port: int = 6379
        max_connections: int = 512
        # 声明redis连接池的decode_responses字段来对键值对进行默认编码
        # 一般情况下，如果redis只存储一些str字符串等键值对，推荐使用decode_responses来避免在代码手动decode -- decode_responses:bool = True
        # 如果存贮的内容涉及：涉及对象，字典，列表等的存储，不使用decode_responses -- decode_responses:bool = False
        decode_responses: bool = False
        encoding = "utf-8"

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        self.app = app
        self._sync_redis = None

        @app.on_event("startup")
        def startup_event():
            self._sync_redis = self.init_sync_redis_pool(setting=self.settings)
            self._sync_redis.set("test", 'SyncRedisPluginClient')
            print(self._sync_redis.get("test"))

            app.sync_redis = self._sync_redis

        @app.on_event("shutdown")
        def shutdown_event():
            if self._sync_redis:
                self._sync_redis.close()
